package com.mall.shopping.services;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.commons.result.ResponseData;
import com.mall.shopping.IProductService;
import com.mall.shopping.constant.GlobalConstants;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.ContentConverter;
import com.mall.shopping.converter.ProductConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.entitys.Panel;
import com.mall.shopping.dal.entitys.PanelContentItem;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dal.persistence.PanelContentMapper;
import com.mall.shopping.dal.persistence.PanelMapper;
import com.mall.shopping.dto.*;
import com.mall.shopping.services.cache.CacheManager;
import com.mall.shopping.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.mall.shopping.converter.ProductDetailConverter;
import com.mall.shopping.dal.entitys.ItemDesc;
import com.mall.shopping.dal.persistence.ItemDescMapper;


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.mall.shopping.constant.GlobalConstants.RECOMMEND_PANEL_ID;

/**
 * @ClassName: ProductServiceImpl
 * @Description:
 * @author: by zjl
 * @Date: 2021/5/22   11:13
 */
/**
 * @ClassName ProductServiceImpl
 * @Description
 * @Author fan
 * @Date 2021/5/22 20:14
 **/

@Slf4j
@Component
@Service
public class ProductServiceImpl implements IProductService {

    @Autowired
    ItemMapper itemMapper;
    @Autowired
    ProductConverter productConverter;
    @Autowired
    ItemDescMapper itemDescMapper;
    @Autowired
    ProductDetailConverter productDetailConverter;
    @Autowired
    PanelMapper panelMapper;
    @Autowired
    PanelContentMapper panelContentMapper;
    @Autowired
    ContentConverter contentConverter;
    @Autowired
    CacheManager cacheManager;

    @Override
    public ProductDetailResponse getProductDetail(ProductDetailRequest request) {
        ProductDetailResponse productDetailResponse = new ProductDetailResponse();
        try {
            request.requestCheck();
            Item item = itemMapper.selectByPrimaryKey(request.getId());
            ProductDetailDto productDetailDto = productDetailConverter.item2ProductDetail(item);
            productDetailDto.setProductImageBig(item.getImageBig());
            String[] images = item.getImages();
            List<String> strings = new ArrayList<>();
            for (String image : images) {
                strings.add(image);
            }
            productDetailDto.setProductImageSmall(strings);
            ItemDesc itemDesc = itemDescMapper.selectByPrimaryKey(request.getId());
            String itemDesc1 = itemDesc.getItemDesc();
            productDetailDto.setDetail(itemDesc1);

            productDetailResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            productDetailResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            productDetailResponse.setProductDetailDto(productDetailDto);
        } catch (Exception e) {
            log.error("ProductServiceImpl.getProductDetail occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(productDetailResponse, e);
        }
        return productDetailResponse;
    }

    @Override
    public AllProductResponse getAllProduct(AllProductRequest request) {
        AllProductResponse response = new AllProductResponse();
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        try {
            //data : ArrayList<ProductDto>

            ArrayList<ProductDto> productDtos = new ArrayList<>();
            // 分页
                    //PageHelper.startPage相当于开启分页,通过拦截MySQL的方式,把你的查询语句拦截下来加limit
                    //放到你执行sql之前就行
            PageHelper.startPage(request.getPage(),request.getSize());
            // 排序
            String orderCol = "created";
            String orderDir = "desc";

            if (request.getSort().equals("1")){
                orderCol = "price";
                orderDir = "asc";
            } else if (request.getSort().equals("-1")){
                orderCol = "price";
                orderDir = "desc";
            }

            // 数据库
            // tb_item  记录了所有商品的详细信息
            List<Item> items = itemMapper.selectItemFront(request.getCid(), orderCol, orderDir,
                    request.getPriceGt(), request.getPriceLte());
            //  分页
            PageInfo<Item> pageInfo = new PageInfo<>(items);
            List<ProductDto> productDtoList = productConverter.items2Dto(items);

            response.setProductDtoList(productDtoList);
            response.setTotal(pageInfo.getTotal());
        } catch (Exception e){
            log.error("ProductServiceImpl.getAllProduct occur Exception : " + e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }

    @Override
    public RecommendResponse getRecommendGoods() {
        RecommendResponse response = new RecommendResponse();
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        try {
            //存在缓存
            String json = cacheManager.checkCache(GlobalConstants.RECOMMEND_PANEL_CACHE_KEY);
            if(StringUtils.isNotBlank(json)){
                List<PanelDto> panelContentItemDtoList = JSON.parseArray(json, PanelDto.class);
                Set<PanelDto> panelDtoSet = new HashSet<>(panelContentItemDtoList);
                response.setPanelContentItemDtos(panelDtoSet);
                return response;
            }
            //不存在缓存
            List<Panel> panels=panelMapper.selectPanelContentById(GlobalConstants.RECOMMEND_PANEL_ID);
            System.out.println(panels);
            if(panels==null||panels.isEmpty()){
                return response;
            }
            Set<PanelDto> panelContentItemDtos = new HashSet<PanelDto>();
            panels.parallelStream().forEach(panel -> {
                List<PanelContentItem> panelContentItems = panelContentMapper.selectPanelContentAndProductWithPanelId(panel.getId());
                PanelDto panelDto = contentConverter.panen2Dto(panel);
                panelDto.setPanelContentItems(contentConverter.panelContentItem2Dto(panelContentItems));
                panelContentItemDtos.add(panelDto);
            });
            response.setPanelContentItemDtos(panelContentItemDtos);
            cacheManager.setCache(GlobalConstants.RECOMMEND_PANEL_CACHE_KEY,JSON.toJSONString(panelContentItemDtos),GlobalConstants.RECOMMEND_CACHE_EXPIRE);

        }catch (Exception e){
            log.error("ProductServiceImpl.getAllProduct Occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;

        }
        //todo:获取推荐商品信息列表
/*        //先获得 List<PanelContentItemDto> panelContentItems
        List<PanelContentItem> panelContentItems = panelContentMapper.selectPanelContentAndProductWithPanelId(RECOMMEND_PANEL_ID);
        List<PanelContentItemDto> panelContentItemDtoList = contentConverter.panelContentItem2Dto(panelContentItems);
        //后获得dto获取panel_content表中type=2的商品, 热门推荐和热门商品
        Panel panel = panelMapper.selectByPrimaryKey(RECOMMEND_PANEL_ID);
        PanelDto panelDto = contentConverter.panen2Dto(panel);
        Set<PanelDto> panelContentItemDtos = new HashSet<>();
        panelContentItemDtos.add(panelDto);
        recommendResponse.setPanelContentItemDtos(panelContentItemDtos);
        return recommendResponse;*/

    private String generatorProduceCacheKey(ProductDetailRequest request){
        StringBuilder stringBuilder=new StringBuilder(GlobalConstants.PRODUCT_ITEM_CACHE_KEY);
        stringBuilder.append(":").append(request.getId());
        return stringBuilder.toString();
    }

}

